#!/usr/bin/env python3
"""
生产环境诊断脚本
"""

import sys
import os
import traceback

print("=== 生产环境诊断 ===")
print(f"Python版本: {sys.version}")
print(f"Python路径: {sys.executable}")
print(f"当前工作目录: {os.getcwd()}")

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)
print(f"项目根目录: {project_root}")

# 切换到项目目录
os.chdir(project_root)
print(f"切换后目录: {os.getcwd()}")

print("\n=== 检查关键文件 ===")
files_to_check = [
    "db/__init__.py",
    "db/models/__init__.py", 
    "db/models/base.py",
    "db/models/file.py",
    "db/models/scan.py"
]

for file_path in files_to_check:
    if os.path.exists(file_path):
        print(f"✅ {file_path} 存在")
    else:
        print(f"❌ {file_path} 不存在")

print("\n=== 测试模块导入 ===")

# 1. 测试基础模块
try:
    print("1. 测试sqlalchemy...")
    import sqlalchemy
    print(f"✅ sqlalchemy版本: {sqlalchemy.__version__}")
except Exception as e:
    print(f"❌ sqlalchemy导入失败: {e}")

# 2. 测试base模块
try:
    print("2. 测试db.models.base...")
    from db.models.base import Base
    print("✅ db.models.base 导入成功")
except Exception as e:
    print(f"❌ db.models.base 导入失败: {e}")
    traceback.print_exc()

# 3. 测试file模块 - 分步测试
try:
    print("3. 测试db.models.file...")
    
    # 先测试文件是否存在
    if not os.path.exists("db/models/file.py"):
        print("❌ file.py文件不存在")
    else:
        print("✅ file.py文件存在")
        
        # 测试文件内容
        with open("db/models/file.py", "r", encoding="utf-8") as f:
            content = f.read()
            print(f"✅ file.py文件可读取，长度: {len(content)}")
            
        # 尝试导入
        from db.models.file import FileUpload, FileAnalysisResult
        print("✅ db.models.file 导入成功")
        
except Exception as e:
    print(f"❌ db.models.file 导入失败: {e}")
    traceback.print_exc()

# 4. 测试完整导入链
try:
    print("4. 测试完整导入链...")
    from db.models import FileUpload, FileAnalysisResult
    print("✅ db.models 导入成功")
except Exception as e:
    print(f"❌ db.models 导入失败: {e}")
    traceback.print_exc()

# 5. 测试startup
try:
    print("5. 测试startup...")
    import startup
    print("✅ startup 导入成功")
except Exception as e:
    print(f"❌ startup 导入失败: {e}")
    traceback.print_exc()

print("\n=== 诊断完成 ===")
